#coding=utf-8
import requests,json,urllib
import re
import pdb
import mysql.connector
import connect_mysql



#引用connect_mysql程序连接数据库
connect_mysql.connect_mysql()

def Input(url, adminname, password,borrow_type, borrowtitle, money, huankuanfangshi, rate, username_type, borrowname, month, cashgroup, agentname,borrow_fee_rate):
    login_headers = {'Referer': url, 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded',
                     'Accept-Encoding': 'gzip, deflate',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    first_headers = {'Referer': url + '/bdadd/bdadd_one/', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded',
                     'Accept-Encoding': 'gzip, deflate',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    second_headers = {'Referer': url + '/bdadd/userinfo/', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                      'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded',
                      'Accept-Encoding': 'gzip, deflate',
                      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    thrid_headers = {'Referer': url + '/bdadd/risk/', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded',
                     'Accept-Encoding': 'gzip, deflate',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    fouth_headers = {'Referer': url + '/bdadd/bdinfo/', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded',
                     'Accept-Encoding': 'gzip, deflate',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}

    try:
        # 通过登录接口登录运营后台
        import time, datetime
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))  # 标的编号命名格式,也为业务编号
        time = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()))
        userinformation = {'adminname': adminname, 'password': password, 'authCode': '123456'}
        s = requests.session()
        login = s.post(url, data=userinformation, headers=login_headers, verify=False)
        login1 = str(login)
        if u"登录成功" in login.text:
            print login1 + u"登录成功"
            # 登录成功后，进入发标页面
            if (username_type == u'11' and borrow_type != 'fdl'):    #为个人借款人时
                first = {'post_type': borrow_type, 'file_number': now, 'borrow_numbers': now, 'name': borrowtitle + now,
                         'username_type': username_type, 'username': borrowname, 'borrow_use': '1', 'account': money,
                         'borrow_period': month, 'borrow_style': huankuanfangshi, 'borrow_apr': rate,
                         'cashgroup': cashgroup, 'agent_username': agentname, 'period_type': 'day','borrow_fee_rate':borrow_fee_rate}
                firstinput = s.post(url + '/bdadd/bdadd_one/', data=first, cookies=login.cookies, headers=first_headers,verify=False)
                print firstinput.text
                # 第二个页面
                # 通过正则获取到借款人的详细信息
                borrow = s.get(url + '/bdadd/userinfo/', cookies=login.cookies, headers=second_headers, verify=False)
                username = re.findall(r'name="username"  value="(.+)" borrow_apr=', borrow.text)
                id_number = re.findall(r'name="id_number" value="(.+)" pattern_idnumber=', borrow.text)
                phone1 = re.findall(r'name="phone1" value="(.+)" phonenum=', borrow.text)
                age = re.findall(r'name="age" id="age" value="(.+)" onfocus=', borrow.text)
                #print username
                if username == []:
                    return u'所填信息有误，请仔细检查并重新填入！'
                else:
                    print username[0], id_number[0], phone1[0], age[0]
                    second = {'username': username[0], 'id_number': id_number[0], 'account_use': u'借钱来耍啊！！！',
                              'phone1': phone1[0], 'age': age[0], 'edu': '4', 'marry': '1','address':u'四川省成都市天府广场','address_now':u'四川省成都市天府广场',
                              'category':'18','provinceId':'2570','cityId':'2571','work_info':u'工作很好！'}
                    secondinput = s.post(url + '/bdadd/userinfo/', data=second, cookies=login.cookies, headers=second_headers,verify=False)

            if (username_type == u'11' and borrow_type == 'fdl'):  #为房东乐时
                first = {'post_type': borrow_type, 'file_number': now, 'borrow_numbers': now, 'name': borrowtitle + now,
                         'username_type': username_type, 'username': borrowname, 'borrow_use': '1', 'account': money,
                         'borrow_period': month, 'borrow_style': huankuanfangshi, 'borrow_apr': rate,
                         'cashgroup': cashgroup, 'agent_username': agentname, 'period_type': 'day','borrow_fee_rate':borrow_fee_rate}
                firstinput = s.post(url + '/bdadd/bdadd_one/', data=first, cookies=login.cookies, headers=first_headers,verify=False)
                print firstinput.text
                # 第二个页面
                # 通过正则获取到借款人的详细信息
                borrow = s.get(url + '/bdadd/userinfo/', cookies=login.cookies, headers=second_headers, verify=False)
                username = re.findall(r'name="username"  value="(.+)" borrow_apr=', borrow.text)
                id_number = re.findall(r'name="id_number" value="(.+)" pattern_idnumber=', borrow.text)
                phone1 = re.findall(r'name="phone1" value="(.+)" phonenum=', borrow.text)
                age = re.findall(r'name="age" id="age" value="(.+)" onfocus=', borrow.text)
                #print username
                if username == []:
                    return u'所填信息有误，请仔细检查并重新填入！'
                else:
                    print username[0], id_number[0], phone1[0], age[0]
                    second = {'username': username[0], 'id_number': id_number[0], 'account_use': u'借钱来耍啊！！！',
                              'phone1': phone1[0], 'age': age[0], 'edu': '4', 'marry': '1', 'address': u'四川省成都市天府广场',
                              'address_now': u'四川省成都市天府广场','fld_type':'1',
                              'category': '18', 'provinceId': '2570', 'cityId': '2571', 'work_info': u'工作很好！'}
                    secondinput = s.post(url + '/bdadd/userinfo/', data=second, cookies=login.cookies, headers=second_headers,verify=False)
                    # 第三个页面
                    thrid = { 'house_type': '1', 'buy_type_house': '1',
                             'build_time': '2017-12',
                             'buy_time': '2018-04-01', 'house_diya_money': '100', 'house_diya_address': u'成都市'+now,
                             'house_basis': u'成都房管所',
                             'house_money': '100', 'house_area': '120', 'house_address': u'四川成都市'+now, 'house_byuser': u'陈奕迅',
                             'house_byuser_type': '1',
                             'house_id': now, 'nums': '1', 'isaddnew': '1'}
                    thrid01 = {'subtype': 'next', 'property_type': '1'}
                    thirdinput = s.post(url + '/bdriskmore/?&nums=1', data=thrid, cookies=login.cookies, headers=thrid_headers,verify=False)
                    thirdinput01 = s.post(url + '/bdadd/risk/', data=thrid01, cookies=login.cookies, headers=thrid_headers,verify=False)
                    # 第四个页面
                    fouth = {'borrow_release_time': time, 'is_awart_type': '0', 'is_mobile_type': '0', 'award_type': '0',
                             'award_status': '2', 'award_scale': '', 'borrow_valid_time': '1', 'tender_account_min': '100',
                             'tender_account_max': '0', 'borrow_password': ''}
                    fouthinput = s.post(url + '/bdadd/bdinfo/', data=fouth, cookies=login.cookies, headers=fouth_headers,verify=False)
                    print fouthinput.text
                    print u"业务编号是：" + now + u",发布时间为：" + time
                    # 进入一审
                    search_data = {'searchType': 'borrow_numbers', 'searchWord': now}
                    search = s.get(url + '/bdverify/index/', params=search_data, cookies=login.cookies, headers=login_headers,verify=False)
                    res_td = r'<td>(.*?)</td>'
                    borrowid0 = re.findall(res_td, search.text, re.S | re.M)
                    borrowid = int(borrowid0[0])
                    print u"借款编号是：" + str(borrowid)
                    # 通过正则取出进入一审的url中的id
                    examineid0 = re.findall(r'/bdverify/verifyone/\?id=(.+)&borrow_nid', search.text)
                    examineid1 = examineid0[0]
                    examineid = examineid1[0:7]
                    #print examineid
                    # print examineid
                    # 进入一审
                    examine01_data = {'id': examineid, 'borrow_nid': borrowid}
                    examine01 = s.get(url + '/bdverify/verifyone/', params=examine01_data, cookies=login.cookies,
                                      headers=login_headers, verify=False)
                    examine01_post_data = {'borrow_status_small': '3', 'remark': u'审核通过'}
                    examine01_post = s.post(examine01.url, data=examine01_post_data, cookies=login.cookies,
                                            headers=login_headers, verify=False)
                    # 提交二审,
                    examine02_url = url + '/bdverify/subtwo/?id=' + str(examineid) + '&borrow_nid=' + str(borrowid)
                    examine02_post_data = {'is_awart_type': '0', 'is_mobile_type': '0', 'award_type': '0', 'award_status': '2',
                                           'award_scale': '', 'borrow_valid_time': '1', 'borrow_release_time': time,
                                           'tender_account_min': '100', 'tender_account_max': '0'}
                    examine02_post = s.post(examine02_url, data=examine02_post_data, cookies=login.cookies,
                                            headers=login_headers, verify=False)
                    # 二审通过
                    examine03_url = url + '/bdverify/verifytwo/?id=' + str(examineid) + '&borrow_nid=' + str(borrowid)
                    examine03_post_data = {'borrow_status_small': '7', 'remark': u'审核通过'}
                    examine03_post = s.post(examine03_url, data=examine03_post_data, cookies=login.cookies,headers=login_headers, verify=False)






            if username_type == u'21':  #为机构借款人时
                # 第一个页面
                first = {'post_type': borrow_type, 'file_number': now, 'borrow_numbers': now, 'name': borrowtitle + now,
                         'username_type': username_type, 'username': borrowname, 'borrow_use': '1', 'account': money,
                         'borrow_period': month, 'borrow_style': huankuanfangshi, 'borrow_apr': rate,
                         'cashgroup': cashgroup, 'agent_username': agentname, 'period_type': 'day','borrow_fee_rate':borrow_fee_rate
                         }
                firstinput = s.post(url + '/bdadd/bdadd_one/', data=first, cookies=login.cookies, headers=first_headers,verify=False)
                print firstinput.text
                # 第二个页面
                #borrow = s.get(url + '/bdadd/userinfo/', cookies=login.cookies, headers=second_headers, verify=False)
                #username = re.findall(r'(.+)                            <span class="r-txt"></span>', borrow.text)
                #print username

                second_jigou = {'account_use': '借钱来耍耍！！！','category': '18'}
                second_jigou_ = s.post(url + '/bdadd/userinfo/', data=second_jigou, cookies=login.cookies,headers=second_headers, verify=False)

            if borrow_type == 'car':  #车易贷
                # 第三个页面
                thrid = {'subtype': 'next', 'property_type': '2','buy_type_car':'1','vouchtype':'1','car_money_luo':'1000000','vin':now}
                thirdinput = s.post(url + '/bdadd/risk/', data=thrid, cookies=login.cookies, headers=thrid_headers,verify=False)

            if borrow_type == 'house':  #房易贷
                # 第三个页面
                thrid = {'subtype': 'next', 'property_type': '1', 'house_type':'1','buy_type_house':'1','build_time':'2017-12',
                         'buy_time':'2018-04-01','house_diya_money':'100','house_diya_address':u'成都市','house_basis':u'成都房管所',
                         'house_money':'100','house_area':'120','house_address':u'四川成都市','house_byuser':u'陈奕迅','house_byuser_type':'1',
                         'house_id':now,'nums':'1','isaddnew':'1'}
                thirdinput = s.post(url + '/bdadd/risk/', data=thrid, cookies=login.cookies, headers=thrid_headers,verify=False)

            if borrow_type == 'ysd':   #烟商贷
                #第三个页面
                thrid = {'subtype': 'next', 'property_type': '1','repay_one':u'经营收入','repay_two':u'经营者自有资金','borrow_userinfo':'<br>',
                         'borrow_log':'<br>','house_type':'1','buy_type_house':'1','build_time':'2017-12',
                         'buy_time':'2018-04-01','house_diya_money':'100','house_diya_address':u'成都市','house_basis':u'成都房管所',
                         'house_money':'100','house_area':'120','house_address':u'四川成都市','house_byuser':u'陈奕迅','house_byuser_type':'1',
                         'house_id':now,'nums':'1','isaddnew':'1'}
                thirdinput = s.post(url + '/bdadd/risk/',data=thrid, cookies=login.cookies, headers=thrid_headers,verify=False)

            if borrow_type == 'gyd':  #供链贷
                # 第三个页面
                thrid = {'subtype': 'next', 'property_type': '1', 'house_type':'1','buy_type_house':'1','build_time':'2017-12',
                         'buy_time':'2018-04-01','house_diya_money':'100','house_diya_address':u'成都市','house_basis':u'成都房管所',
                         'house_money':'100','house_area':'120','house_address':u'四川成都市','house_byuser':u'陈奕迅','house_byuser_type':'1',
                         'house_id':now,'nums':'1','isaddnew':'1','repay_one':u'经营收入','repay_two':u'经营者自有资金','borrow_userinfo':u'更多借款人信息！！！','borrow_log':u'风控介绍！！！'}
                thirdinput = s.post(url + '/bdadd/risk/', data=thrid, cookies=login.cookies, headers=thrid_headers,verify=False)

            if borrow_type != 'fdl':  #标类不为房东乐时才执行批次号管理
                # 第四个页面
                fouth = {'borrow_release_time': time, 'is_awart_type': '0', 'is_mobile_type': '0', 'award_type': '0',
                         'award_status': '2', 'award_scale': '', 'borrow_valid_time': '1', 'tender_account_min': '100',
                         'tender_account_max': '0','borrow_password':''}
                fouthinput = s.post(url + '/bdadd/bdinfo/', data=fouth, cookies=login.cookies, headers=fouth_headers,verify=False)
                #print fouthinput.text
                print u"业务编号是：" + now + u",发布时间为：" + time
                #生成批次号
                picihao_search_data = {'searchType':'borrow_numbers','searchWord':now}
                picihao_search = s.get(url+'/bdbatch/index/',params=picihao_search_data, cookies=login.cookies, headers=login_headers,verify=False)
                #通过正则取出借款编号
                '''
                res_td = r'<td>(.*?)</td>'
                borrowid0 = re.findall(res_td, picihao_search.text, re.S | re.M)
                print borrowid0
                borrowid = int(borrowid0[0])
                print u"借款编号是：" + str(borrowid)
                '''
                borrowid0 = re.findall(r'value="(.+)" /></td>',picihao_search.text)
                borrowid = borrowid0[0]
                print u"借款编号是：" + str(borrowid)
                #提交
                SelectCheckdBd_data = {'borrow_nid':borrowid,'checked':'true'}
                SelectCheckdBd_post = s.post(url+'/bdbatch/ajaxSelectCheckdBd/',data=SelectCheckdBd_data,cookies=login.cookies, headers=login_headers,verify=False)
                picihao01_data = {'str':'1'}
                #picihao01 = s.get(url+'/bdbatch/ajaxSelectList/',params=picihao01_data,cookies=login.cookies, headers=login_headers,verify=False)
                picihao02 = s.get(url+'/bdbatch/ajaxsubmit/',params=picihao01_data,cookies=login.cookies, headers=login_headers,verify=False)
                picihao03 = s.get(url+'/bdbatch/batched/',params=picihao_search_data, cookies=login.cookies, headers=login_headers,verify=False)
                #通过正则获取批次号
                picihao = re.findall(r'value="(.+)" /></td>',picihao03.text)
                picihaoid = picihao[0]
                picihao02_data = {'str':picihaoid}
                picihao04 = s.get(url+'/bdbatch/subverify/',params=picihao02_data,cookies=login.cookies, headers=login_headers,verify=False)
                # 进入一审
                search_data = {'searchType': 'borrow_numbers', 'searchWord': now}
                search = s.get(url + '/bdverify/index/', params=search_data, cookies=login.cookies, headers=login_headers,verify=False)
                # 通过正则取出进入一审的url中的id
                examineid0 = re.findall(r'/bdverify/verifyone/\?id=(.+)&borrow_nid', search.text)
                examineid1 = examineid0[0]
                examineid = examineid1[0:8]
                #print examineid
                print examineid
                # 进入一审
                examine01_data = {'id': examineid, 'borrow_nid': borrowid}
                examine01 = s.get(url + '/bdverify/verifyone/', params=examine01_data, cookies=login.cookies,headers=login_headers, verify=False)
                examine01_post_data = {'borrow_status_small': '3', 'remark': u'审核通过'}
                examine01_post = s.post(examine01.url, data=examine01_post_data, cookies=login.cookies,headers=login_headers, verify=False)
                # 提交二审
                #pdb.set_trace()   #断点
                examine02_url = url + '/bdverify/subtwo/?id=' + str(examineid) + '&borrow_nid=' + str(borrowid)
                examine02_post_data = {'is_awart_type': '0', 'is_mobile_type': '0', 'award_type': '0', 'award_status': '2',
                                       'award_scale': '', 'borrow_valid_time': '1', 'borrow_release_time': time,
                                       'tender_account_min': '100', 'tender_account_max': '0'}
                examine02_post = s.post(examine02_url, data=examine02_post_data, cookies=login.cookies,headers=login_headers, verify=False)
                # 二审通过
                examine03_url = url + '/bdverify/verifytwo/?id=' + str(examineid) + '&borrow_nid=' + str(borrowid)
                examine03_post_data = {'borrow_status_small': '7', 'remark': u'审核通过'}
                examine03_post = s.post(examine03_url, data=examine03_post_data, cookies=login.cookies,headers=login_headers, verify=False)
                #print examine03_post.text
                #出队列
                if url == 'http://op.yidai.co':
                    out = s.get('http://task.yidai.co/worthautoissue.task.php')
                    print out.text
                if url == 'http://op.yidai.cc':
                    out = s.get('http://task.yidai.cc/worthautoissue.task.php')
                    print out.text
                if url == 'http://op.yidaip2p.net':
                    out = s.get('http://task.yidaip2p.net/worthautoissue.task.php')
                    print out.text




        else:
            return  u"登录失败,请确认账号和密码是否匹配"

        # 进行数据库写入
        connect = connect_mysql.connect_mysql()[0]  # connect是由connect_mysql函数返回的第一个值
        cursor = connect.cursor()
        # SQL 插入语句
        sql = "insert into mysql.edai_borrow(url,username,agent_username,borrowname,post_type,amount_type,account,borrow_nid,borrow_style,borrow_period,borrow_apr,borrow_username,modify_time,borrow_numbers) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
        url, borrowname, agentname, borrowtitle, borrow_type, borrow_type, money, borrowid, huankuanfangshi, month,rate,borrowname, time, now)
        print sql
        # 执行sql语句
        input = cursor.execute(sql)
        connect.commit()  # 实例提交命令
        #cursor.close()
        #connect.close()
        print("insert ok")

        return u"借款标题是：" + borrowtitle + now + u",借款人是：" + borrowname + u"，借款编号是：" + str(borrowid)

    except:
        return u"请仔细检查所填内容并再次尝试！"


